<%@ page import="com.cinsea.form.model.Formviewfield" %>
<%@ page import="com.cinsea.security.service.RightService" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="com.cinsea.form.model.Formprocess" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ include file="/common/common.jsp" %>


<html>
<%
    response.setHeader("cache-control", "no-cache");
            response.setHeader("pragma", "no-cache");
            response.setHeader("expires", "Mon 1 Jan 1990 00:00:00 GMT");
        Map workflowparameters = new HashMap();
        String directoryid = StringUtil.null2String(request.getParameter("directoryid")).trim();

            String formid ="ut_research";
        	String id = StringUtil.null2String(request.getParameter("processid")).trim();
        	String nodeid = StringUtil.null2String(request.getParameter("nodeid")).trim();
            FormprocessService formprocessService=(FormprocessService) Env.getBean("formprocessService");
        FormdataService fs = (FormdataService) Env.getBean("formdataService");
            FormviewService formviewService= (FormviewService) Env.getBean("formviewService");
            FormprocessService fbs = (FormprocessService) Env.getBean("formprocessService");
            DirectoryService cs = (DirectoryService) Env.getBean("directoryService");
        	FormviewService fls = (FormviewService) Env.getBean("formviewService");
        	Directory directory = cs.getDirectoryById(directoryid);
            FormService formService=(FormService) Env.getBean("formService");
            RightService rightService = (RightService) Env.getBean("rightService");
        workflowparameters.put("dowid", directoryid);
        	workflowparameters.put("processid",id);
        	workflowparameters.put("nodeid",nodeid);

        	String becreate = "0"; //是否新建表单
    if(!StringUtil.isEmpty(id)){
    		becreate = "0";
            Formprocess formprocess= fbs.get(id);
            if(formprocess.getDeleted().intValue()==1){
    			response.sendRedirect(request.getContextPath()+"/nodata.jsp");
    			return;
    		}
            if(StringUtil.isEmpty(directoryid)){
            directoryid =formprocess.getDowid();
            directory =cs.getDirectoryById(directoryid);
            }
        }
        workflowparameters.put("becreate",becreate);
            String initparameterstr=null;
            Map jsonObject=new HashMap();
            Map initparameters = new HashMap();
        	for( Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
        		String pName = e.nextElement().toString().trim();
        		String pValue = StringUtil.trimToNull(request.getParameter(pName));
        		if(!StringUtil.isEmpty(pName)){
        			initparameters.put(pName,pValue);
                    if(!StringUtil.isEmpty(pValue))
                    jsonObject.put(pName,pValue);

                }
            }
            initparameterstr= JSON.toJSONString(jsonObject);
        	workflowparameters.put("initparameters",initparameters);
        	//处理输入参数完成

        	workflowparameters.put("formviewtype","2");
        if(becreate.equals("1")){
        		boolean isauth = rightService.checkOpttype(directoryid, 2);
        		if(!isauth){
        			response.sendRedirect(request.getContextPath()+"/nopermit.jsp");
        			return;
        		}
                workflowparameters.put("formviewtype","2");
            }
        workflowparameters.put("onlyread","0");
        	workflowparameters.put("processtype","2");
        workflowparameters.put("formid",formid);
        Form form=formService.getFormById(formid);
                        Env.setDowid(directoryid);
                        Env.setTablename(form.getTablename());

        	String viewid="";
        workflowparameters = fs.getFormdata(workflowparameters);
            viewid = StringUtil.null2String(workflowparameters.get("viewid"));
        	String needcheckfields = StringUtil.null2String(workflowparameters.get("needcheck"));
        	String formcontent = StringUtil.null2String(workflowparameters.get("formcontent"));


        	String fieldcalscript = StringUtil.null2String(workflowparameters.get("fieldcalscript"));
            String onaddrowscript = StringUtil.null2String(workflowparameters.get("onaddrowscript"));
            String triggercalscript= StringUtil.null2String(workflowparameters.get("triggercalscript"));
            String ufscript= StringUtil.null2String(workflowparameters.get("ufscript"));
            String directscript= StringUtil.null2String(workflowparameters.get("directscript"));
            FormfieldService formfieldService = (FormfieldService) Env.getBean("formfieldService");
    pagemenustr += "addBtn(tb,'" + I18n.getText("submit") + "','S','accept',function(){onSubmit()});";
    pagemenustr += "addBtn(tb,'" + I18n.getText("cancel") + "','C','cancel',function(){onCancel()});";


%>


<head>
<%@ include file="/common/head.jsp" %>
    <script src='${ctx}/dwr/interface/DataService.js'></script>
    <script src='${ctx}/dwr/interface/OptionService.js'></script>
    <script src='${ctx}/dwr/util.js'></script>
<script type="text/javascript">
Ext.onReady(function() {
    Ext.QuickTips.init();
    <%if(!pagemenustr.equals("")){%>
    var tb = new Ext.Toolbar();
    tb.render('pagemenubar');
    <%=pagemenustr%>
    <%}%>
});

var needchecklists = "<%=needcheckfields%>";
var id = "<%=StringUtil.null2String(id)%>";
var dowid = "<%=StringUtil.null2String(directoryid)%>";
var nodeid = "<%=StringUtil.null2String(nodeid)%>";
</script>
    <script type="text/javascript">

        function onCancel(){
                window.history.go(-1);
            }
    </script>
    <script type="text/javascript">

        function getBrowser(viewurl, inputname, inputspan, isneed) {
            var id;
            try {
                id = showDialog(viewurl);
            } catch(e) {
            }
            if (id != null) {
                if (id[0] != '0') {
                    document.getElementById(inputname).value = id[0];
                    document.getElementById(inputspan).innerHTML = id[1];
                } else {
                    document.getElementById(inputname).value = '';
                    if (isneed == '0')
                        document.getElementById(inputspan).innerHTML = '';
                    else
                        document.getElementById(inputspan).innerHTML = "<img src='${ctx}/images/base/checkinput.gif>'";

                }
            }
        }


        $(document).keydown(function(event) {
            if (event.keyCode == 13) {
                onSubmit();
            }
        });

        function onSubmit(){
          checkfields="title,"+needchecklists;
          checkmessage="<%=I18n.getText("mustfill")%>";

          var needcheck = 1;


          if(needcheck == 1){
        	  if(checkForm(mainForm,checkfields,checkmessage)){
                  $("input[name^='checknode_']").each(function() {
                      el = this.parentNode;
                      while (el && el.tagName != "TR") {
                          el = el.parentNode;

                      }
                      this.nextSibling.value = el.rowIndex;
                  })


            for(var num=0;num<objectKey.length;num++){
                if(objectKey[num]!=""&&objectKey[num]!=null){
                    getMapValue(objectKey[num]);
                    if(timevalue==document.getElementById(objectKey[num]).value){
                        document.getElementById(objectKey[num]).value="$currenttime$";
                    }
                }
            }
                       document.mainForm.submit();

        	  }
          }
        }
    </script>
    <script type="text/javascript">
        function setBrowser(inputname,inputspan,browserid,param,viewurl,isneed){
            id=ReturnValue;
            var fieldfunc=-1;
            if(param)
             fieldfunc=param.indexOf("function:");
            if (id!=null) {
        if (id[0] != '0') {
            document.getElementById(inputname).value = id[0];
            if(!Ext.isIE) $('#'+inputname).trigger("AttrModified");
    		document.getElementById(inputspan).innerHTML = id[1];
              if(fieldfunc>-1){
              funcname=param.substring(9);
          scripts="valid="+funcname+"('"+id[0]+"');";
            eval(scripts) ;
            if(!valid){  //valid默认的返回true;
             document.getElementById(inputname).value = '';
    		if (isneed=='0')
    		document.getElementById(inputspan).innerHTML = '';
    		else
    		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';
              }
              }
        }else{
    		document.getElementById(inputname).value = '';
            if(!Ext.isIE) $('#'+inputname).trigger("AttrModified");
    		if (isneed=='0')
    		document.getElementById(inputspan).innerHTML = '';
    		else
    		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';

                }
             }
        }
        function getBrowser(inputname,inputspan,browserid,param,viewurl,isneed){
            ReturnValue=null;
            var fieldfunc=-1;
            if(param)
              fieldfunc=param.indexOf("function:");
            if(fieldfunc>-1){}else{
                var param = parserRefParam(inputname,param);
            }
    	var idsin = document.getElementsByName(inputname)[0].value;
    	var id;
        try{
             var url ='${ctx}/browser/browser.jsp?id='+browserid+'&'+param+'&idsin='+idsin
                if (idsin.length > 900) {   //当idsin过长时，ie的url不支持过长的地址
                    url ='${ctx}/browser/browser.jsp?id='+browserid+'&'+param;
                }
        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))|| (navigator.userAgent.match(/iPad/i))|| (navigator.userAgent.match(/Android/i)))
        id=showDialog(url,null,null,function(){
            setBrowser(inputname,inputspan,browserid,param,viewurl,isneed) ;
        });
        else
        id=showDialog(url);
        }catch(e){return}
        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))|| (navigator.userAgent.match(/iPad/i))|| (navigator.userAgent.match(/Android/i)))
        ;
        else
        setBrowser(inputname,inputspan,browserid,param,viewurl,isneed);

        }
        function  addBrowser(inputname,inputspan,doctype,viewurl,isneed,docdir){
            params = ""
            targeturl = "<%=URLEncoder.encode("/common/closedialog.jsp", "UTF-8")%>"
            var id;
            try{
                id = showDialog("${ctx}/document/documentcreate.jsp?directoryid="+docdir+"&doctype="+doctype+params+"&targeturl="+targeturl,"dialogHeight:"+screen.availHeight+"px;dialogWidth:"+screen.availWidth+"px; center: Yes; help: No; resizable: yes; status: No");

            }catch(e){return}
              if (id!=null) {

        if (id[0] != '0') {
    		document.getElementById(inputname).value = id[0];
    		document.getElementById(inputspan).innerHTML = id[1];
        }else{
    		document.getElementById(inputname).value = '';
    		if (isneed=='0')
    		document.getElementById(inputspan).innerHTML = '';
    		else
    		document.getElementById(inputspan).innerHTML = '<img src=${ctx}/images/base/checkinput.gif>';

                }
             }
        }
    </script>
</head>
<body>
<div id="pagemenubar"></div>
<div>
    <form  id="mainForm" name="mainForm" method="post" enctype="multipart/form-data" action="${ctx}/formdata.do" target="_self">
            <input type="hidden" name="action" value="createformdata">
            <input type="hidden" name="targeturl" value="/research/researchview.jsp">
            <input type="hidden" name="dowid" id="dowid" value="<%=directoryid%>">
            <input type="hidden" name="formid" id="formid" value="<%=formid%>">
            <input type="hidden" name="viewid" id="viewid" value="<%=viewid%>">
            <input type="hidden" name="creator" id="creator" value="<%=Env.getRemoteUser().getCurrentuserid()%>">
            <input type="hidden" name="processid" id="processid" value="<%=id%>">
            <input type="hidden" name="nodeid" value="<%=nodeid%>">

            <input type="hidden" name="editmode" value="1">
            <input type="hidden" name="currentuserid" value="<%=Env.getRemoteUser().getCurrentuserid()%>">
            <input type="hidden" name="becreate" value="<%=becreate%>">
            <input type="hidden" name="initparameterstr" value='<%=initparameterstr%>'>
                <table class=noborder>
            				<colgroup>
            					<col width="20%">
            					<col width="80%">
            				</colgroup>

            	</table>

            <%=formcontent%>
            <input type="hidden" name="tmpvalue" id="tmpvalue" value="">
        </form>
</div>
<script type="text/javascript" language="javascript" src="<%= request.getContextPath()%>/datapicker/WdatePicker.js"></script>
</body>

<script language="javascript">
function formatTables() {
          if (needformatted) {
              Ext.each(Ext.query("table[id*='oTable']"), function() {
                  formatTable(this);
              });
              Ext.each(Ext.query("table[id*='oTable']"), function() {
                  this.onresize=function(){formatTable(this)};
              });
          }
      }
var inputid;
var spanid;
var temp;
[].indexOf || (Array.prototype.indexOf = function(v)
{
for(var i = this.length; i-- && this[i] !== v;);
return i;
}
);

$(document).ready(function($){
  <%=ufscript%>
  <%=directscript%>
 $.Autocompleter.Selection = function(field, start, end) {
       var flag;
     if(Ext.isIE){
       flag= field.createTextRange; //在firefox下span不显示 原因是因为  firefox不支持createTextRange
     }else{
       flag=true;
     }
     if(flag){
         if (Ext.isIE) {
             var selRange = field.createTextRange();
             selRange.collapse(true);
             selRange.moveStart("character", start);
             selRange.moveEnd("character", end);
             selRange.select();
         }
      if(inputid==undefined||spanid==undefined)
         return;
       var len=field.value.indexOf("  ");
         var lenspance=field.value.indexOf(" ");
           if(temp==0&&len>0){
           temp=1;
       var  length=field.value.length;
         var data=field.value;
      document.getElementById(inputid).value=field.value.substring(0,field.value.indexOf("  "));
     document.getElementById(spanid+'span').innerHTML= data.substring(len,length);
       }else if(temp==0&&lenspance>0){

         var data=field.value;
      document.getElementById(inputid).value=data;
     document.getElementById(spanid+'span').innerHTML= data;
           }else
           {
             document.getElementById(inputid).value="";

           }
} else if( field.setSelectionRange ){
      field.setSelectionRange(start, end);
} else {
         if( field.selectionStart ){
	field.selectionStart = start;
	field.selectionEnd = end;
}
}
field.focus();
};

});

var strSQLs = new Array();
var strValues = new Array();
 <%=triggercalscript%>
function checkUnique(obj,param,isonly,fieldname,tablename){
  if(obj.value.trim()=='')
  return;
   if(isonly==1||param=="")
   {
      param="select "+fieldname+" from "+tablename+" where "+fieldname+" = ?";
   }
  param=param.replace("?","'"+obj.value.ReplaceAll("'","''")+"'");
 if(SQL(param)!=''){
    alert('数据已存在,请重新输入！') ;
    obj.value='';
    obj.focus();
 }

}
function checkdirect(obj)
{
    inputid=obj.id;
    spanid=obj.name.substring(1);
    temp=0;
}
function SQL(param){
		//param = encode(param);

		if(strSQLs.indexOf(param)!=-1){
			var retval = getValidStr(strValues[strSQLs.indexOf(param)]);
			return retval;

		}else{
                  var _url= "${ctx}/data.do";
                  var retval;
                  Ext.Ajax.request({
                      url:_url,
                      sync:true,
                      params:{sql:param},
                      success: function(res) {
                                var doc=res.responseText;
                          retval = getValidStr(doc);
                          strSQLs.push(param);
                          strValues.push(retval);
                      }
                  });
			return retval;
		}
	}
function onCal(){
try{

	var rowindex = 0;
<%=fieldcalscript%>


	function SUM(param){
		var result = 0;
		for(index=0;index<rowindex;index++){
			tmpval = 0;
			try{
			tmpval = eval(param)*1;
			}catch(e){
			tmpval = 0;
			}
			//alert(tmpval);
			result += tmpval;
		}
		rowindex = 0;
		return result;
	}

	function RMB(param){
		var tmpval = eval(param)*1;
		var result =  convertCurrency(tmpval);
		return result;
	}
	function COUNT(param){
		var result = 0;
		for(index=0;index<rowindex;index++){
			tmpval = 0;
			try{
			tmpval = eval(param)*1;
			}catch(e){
			tmpval = 0;
			}
			if(tmpval != 0)
				result ++;
		}
		rowindex = 0;
		return result;
	}
	function PROD(param){
		var result = 1;
		for(index=0;index<rowindex;index++){
			tmpval = 1;
			try{
			tmpval = eval(param)*1;
			}catch(e){
			tmpval = 1;
			}
			//alert(tmpval);
			result = result * tmpval;
		}
		rowindex = 0;
		return result;
	}
	function MAX(param){
		var result = 0;
		for(index=0;index<rowindex;index++){
			tmpval = 0;
			try{
			tmpval = eval(param)*1;
			}catch(e){
			tmpval = 0;
			}
			if(tmpval > result)
				result = tmpval;
		}
		rowindex = 0;
		return result;
	}



}catch(e){}
}
function onAddRow(){
try{
          <%=onaddrowscript%>
}catch(e){}
}

    var rowheightmap=[];
    function formatTable(t) {
             var rowheight = 42;
             var rowheighttmp;
             var rowlist=[]; //max height of each row
             Ext.each(Ext.query("table[class='subformdetailtable']", t), function () {
                 rowcount = this.rows.length;
                 for (i = 0; i < rowcount; i++) {
                     rowheighttmp = this.rows[i].clientHeight;
                     if(!rowlist[i]) {
                         rowlist[i]=rowheighttmp;
                     }
                     if (rowheighttmp > rowlist[i]) rowlist[i] = rowheighttmp;
                     if (rowheighttmp > rowheight) rowheight = rowheighttmp;
                 }
             });
             rowheightmap[t.id]=rowheight; //max row height for each detail table
             if(rowheight<=42) return;
             Ext.each(Ext.query("table[class='subformdetailtable']", t), function () {
                 rowcount = this.rows.length;
                 if (rowcount > 10)
                     caldelay = 10000;
                 for (i = 0; i < rowcount; i++) {
                     this.rows[i].cells[0].style.height = rowlist[i];
                 }
             });
         }
onAddRow();
if (Ext.isIE) {
       inputs = document.mainForm.getElementsByTagName("input");
       for (i = 0; i < inputs.length; i++) {
           inputel = inputs[i];
           if (inputel.value && inputel.value != '')
               inputel.fireEvent('onpropertychange');
       }
   }else{
       $('input').trigger("AttrModified");
   }
var task=new Ext.util.DelayedTask(onCal);
</script>

<script language="javascript">
  //jsmap
  var objectKey = new Array(100);
  var objectValue = new Array(100);
  var timevalue = "";
  function getMapValue(key){
      for(var i=0;i<objectKey.length;i++){
          if(objectKey[i]==key){
              timevalue = objectValue[i];
          }
      }
  }

<%
List list = formviewService.findFormviewfieldByViewid(viewid);
Map map = new HashMap();
for (int i = 0; i < list.size(); i++) {
Formviewfield formviewfield =(Formviewfield) list.get(i);
if("$currenttime$".equals(formviewfield.getFormula()==null?"":formviewfield.getFormula().trim())){
  %>
      if(document.getElementById("<%=formviewfield.getFieldid()%>")!=null){
          objectKey[<%=i%>]="<%=formviewfield.getFieldid()%>";
          objectValue[<%=i%>]=document.getElementById("<%=formviewfield.getFieldid()%>").value;
      }else{
          var i=0;
          while(document.getElementById("<%=formviewfield.getFieldid()%>_"+i)!=null){
              objectKey[<%=i++%>]="<%=formviewfield.getFieldid()%>_"+i;
              objectValue[<%=i++%>]=document.getElementById("<%=formviewfield.getFieldid()%>_"+i).value;
              i++;
          }
      }
  <%
      }
}%>


function onPopup(url){
var id=showDialog("${ctx}"+url);
}
function onEdit(){
  window.location="${ctx}/form/formprocess.jsp?editmode=1&directoryid=<%=directoryid%>&processid=<%=id%>";
}
function onDelete(id) {
      yes('<%=I18n.getText("deleteConfirm")%>', function() {
          Ext.Ajax.request({
              url:'${ctx}/formdata.do?action=delete',
              sync:true,
              params:{processid:'<%=id%>'},
              success: function(res) {
                  var result = res.responseText;
                  if (result == 'success') {
                      pop("删除成功")

                  } else {
                      pop(result)
                  }
              }
          });
      })
  }

function checkFileSize(filepath,maxSize){
  var size=getFileSize(filepath);
  if(size>maxSize)
  return false;
  return true;
}
function getFileSize(filepath){
if(filepath=='')
{
return null;
}
try
{
filecheck.FilePath=filepath;
var size=filecheck.getFileSize()/(1024*1024);
   return size;
}
catch(e)
{
alert(e);
return null;
}
return null;
}
</script>
</html>